import XLSX from 'xlsx';
import { Notification } from 'element-ui';
import BigNumber from 'bignumber.js';
import { isNaN, omit } from 'lodash';
import shortId from 'shortid';
import { TOP_CHANNELS } from '@/constants';
import { convertTimeToNumUtil, getTaskFileValidInfo, getTaskListValidInfo } from './util';

const getMathFloorNum = num => {
  let newNum = typeof num === 'string' ? num.trim() : num;
  if (!newNum && typeof newNum !== 'number') {
    return null;
  }
  newNum = +newNum;
  return isNaN(newNum) ? null : +new BigNumber(newNum).toFixed(2);
};

const INITIAL_TASK = {
  startTime: '00:00',
  endTime: '00:00',
  fileList: [],
  fileData: [],
  errMsg: '',
  showErrMsg: false,
};

export default {
  name: 'manual-price-adjust-price-by-range-modal',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    okBtnLoading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      topChannelList: TOP_CHANNELS.filter(item => item.id === 'MTWM'),
      formValue: {
        topChannelCode: 'MTWM',
      },
      taskList: [],
    };
  },
  methods: {
    onAddTimeRange() {
      this.taskList = [...this.taskList, { ...INITIAL_TASK, id: shortId.generate() }];
    },
    onRemoveTimeRange({ id }) {
      this.taskList = this.taskList.filter(item => item.id !== id);
    },
    onUploadChange({ id }, e, isExceed) {
      const file = isExceed ? { name: e[0]?.name, percentage: 0, status: 'ready', uid: +new Date(), raw: e[0] } : e;
      if (!file?.raw) {
        return;
      }
      const reader = new FileReader();
      reader.onload = e => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'buffer' });
        const [sheetName] = workbook.SheetNames;
        const sheetInfo = workbook.Sheets[sheetName];
        const parsedSheetInfo = XLSX.utils.sheet_to_json(sheetInfo) || [];
        const result = parsedSheetInfo.map((item, index) => {
          const costPrice = String(item['成本价'] || '').trim();
          const cellularCode = String(item['所属蜂窝'] || '').trim();
          const newChannelPrice = String(item['调原价'] || '').trim();
          const limitFrequency = String(item['限购频率'] || '').trim();
          const limitNum = String(item['限购数量'] || '').trim();
          const newActivityPrice = String(item['调特价'] || '').trim();
          const cellularSales = String(item['蜂窝总销量'] || '').trim();
          const activityPriceLimit = String(item['特价限购'] || '').trim();
          const channelPrice = String(item['商品原价'] || '').trim();
          const competeChannelPrice = String(item['竞对原价最低价'] || '').trim();
          const competeActivityPrice = String(item['竞对特价最低价'] || '').trim();
          const competeMaxSales = String(item['竞对最高销量'] || '').trim();
          const retailPrice = String(item['零售价'] || '').trim();
          const activityPrice = String(item['商品特价'] || '').trim();
          const salesRank = String(item['销售排名'] || '').trim();
          const monthSales = String(item['月售'] || '').trim();

          return {
            rowNo: index + 2,
            goodsCode: String(item['商品编码'] || '').trim(),
            channelCode: String(item['渠道编码'] || '').trim(),
            minPrice: String(item['起送价'] || '').trim(),
            ...(channelPrice ? { channelPrice: getMathFloorNum(channelPrice) } : {}),
            ...(cellularCode ? { cellularCode } : {}),
            ...(costPrice ? { costPrice: getMathFloorNum(costPrice) } : {}),
            ...(newChannelPrice ? { newChannelPrice: getMathFloorNum(newChannelPrice) } : {}),
            ...(limitFrequency ? { limitFrequency: getMathFloorNum(limitFrequency) } : {}),
            ...(limitNum ? { limitNum: getMathFloorNum(limitNum) } : {}),
            ...(newActivityPrice ? { newActivityPrice: getMathFloorNum(newActivityPrice) } : {}),
            ...(activityPriceLimit ? { activityPriceLimit: getMathFloorNum(activityPriceLimit) } : {}),
            ...(competeChannelPrice ? { competeChannelPrice: getMathFloorNum(competeChannelPrice) } : {}),
            ...(competeActivityPrice ? { competeActivityPrice: getMathFloorNum(competeActivityPrice) } : {}),
            ...(competeMaxSales ? { competeMaxSales: getMathFloorNum(competeMaxSales) } : {}),
            ...(cellularSales ? { cellularSales: getMathFloorNum(cellularSales) } : {}),
            ...(retailPrice ? { retailPrice: getMathFloorNum(retailPrice) } : {}),
            ...(activityPrice ? { activityPrice: getMathFloorNum(activityPrice) } : {}),
            ...(salesRank ? { salesRank: getMathFloorNum(salesRank) } : {}),
            ...(monthSales ? { monthSales: getMathFloorNum(monthSales) } : {}),
          };
        });
        // 获取数据校验结果
        const { isValid, errMsg } = getTaskFileValidInfo(result);
        // 校验失败
        if (!isValid) {
          // 清空已上传的文件列表
          this.$refs[`uploadRef-${id}`]?.[0]?.clearFiles();
          // 更新 taskList
          this.taskList = this.taskList.map(item => ({
            ...item,
            ...(item.id === id ? { fileList: [], fileData: [] } : {}),
          }));
          Notification({ title: '提示', type: 'error', message: errMsg });
          return;
        }
        // 更新 taskList
        this.taskList = this.taskList.map(item => ({
          ...item,
          ...(item.id === id ? { fileList: [file], fileData: result } : {}),
        }));
        Notification({ title: '提示', type: 'success', message: '文件上传成功' });
      };
      reader.readAsArrayBuffer(file.raw);
    },
    onOpen() {
      this.taskList = [{ ...INITIAL_TASK, id: shortId.generate() }];
    },
    onClose() {
      this.$emit('close');
    },
    onOK() {
      const realTaskList = this.taskList.reduce((prev, curr, index) => {
        const newStartTime = curr.startTime ? convertTimeToNumUtil(curr.startTime) : null;
        const newEndTime = curr.endTime
          ? (curr.endTime === '00:00' && convertTimeToNumUtil('23:59:59')) || convertTimeToNumUtil(curr.endTime) - 1000
          : null;
        if (newStartTime && newEndTime && newEndTime < newStartTime) {
          return [
            ...prev,
            {
              ...curr,
              rowIndex: index + 1,
              startTime: curr.startTime,
              endTime: '00:00',
              startTimeStamp: newStartTime,
              endTimeStamp: convertTimeToNumUtil('23:59:59'),
            },
            {
              ...curr,
              rowIndex: index + 1,
              startTime: '00:00',
              endTime: curr.endTime,
              startTimeStamp: convertTimeToNumUtil('00:00:00'),
              endTimeStamp: newEndTime,
            },
          ];
        }
        return [
          ...prev,
          {
            ...curr,
            rowIndex: index + 1,
            startTimeStamp: newStartTime,
            endTimeStamp: newEndTime,
          },
        ];
      }, []);
      const { isValid, errMsg } = getTaskListValidInfo(realTaskList);
      if (!isValid) {
        Notification({ title: '提示', type: 'error', message: errMsg });
        return;
      }
      // 转成服务端需要的数据格式
      const serveData = this.taskList.map(item => {
        return {
          startTime: item.startTime,
          endTime: item.endTime,
          taskDetails: item.fileData.map(taskItem => ({
            ...omit(taskItem, ['id', 'rowNo', 'newChannelPrice', 'newActivityPrice', 'limitFrequency', 'limitNum', 'activityPriceLimit']),
            activityData: {
              channelCode: taskItem.channelCode,
              goodsCode: taskItem.goodsCode,
              newChannelPrice: taskItem.newChannelPrice,
              newActivityPrice: taskItem.newActivityPrice,
              limitFrequency: taskItem.limitFrequency,
              limitNum: taskItem.limitNum,
              activityPriceLimit: taskItem.activityPriceLimit,
            },
          })),
        };
      });
      this.$emit('ok', { timeTasks: serveData, ...this.formValue });
    },
  },
};
